//
//  MainViewController.swift
//  weibo10
//
//  Created by 晁岳山 on 15/10/14.
//  Copyright © 2015年 晁岳山. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
       addChildViewControllers()
       addCenterBtn()
    }
    
    override func viewWillAppear(animated: Bool) {
        //会创建tabBar中的所有控件
        super.viewWillAppear(animated)
//        print(tabBar.subviews)
        //把按钮拿到前面来
        tabBar.bringSubviewToFront(btn)
    }
    //按钮的监听方法
    //如果单纯的使用private，将无法向运行循环中添加消息，程序会崩溃
    //添加上 @objc修饰符 则可以想运行循环添加消息 即使被标记为private
    //MARK: - 加号按钮点击事件
    @objc private func click(){
        //modal出一个控制器
        var vc: UIViewController
        if !UserAccountViewModel.sharedUserViewMModel.login {
            vc = MainViewController()
        }else {
            vc = ComposeViewController()
        }
        let nav = UINavigationController(rootViewController: vc)
        vc.view.backgroundColor = UIColor.whiteColor()
        presentViewController(nav, animated: true, completion: nil)
    }
    //懒加载按钮
    private lazy var btn: UIButton = UIButton(imageName: "tabbar_compose_icon_add", backImageName: "tabbar_compose_button")
    //添加一个按钮
    func addCenterBtn() {
        let count = childViewControllers.count
        //减一是为了有一个很小的间距
        let  w = tabBar.bounds.width / CGFloat(count) - 1
        btn.frame = CGRectInset(tabBar.bounds, 2 * w, 0)
        tabBar.addSubview(btn)
        //添加按钮监听事件
        btn.addTarget(self, action: "click", forControlEvents: UIControlEvents.TouchUpInside)
    }
    
    /// 创建4个控制器添加到tabBar上
    func addChildViewControllers() {
        
        //设置点击后的颜色  能用颜色解决  最好不用图片 颜色性能高
        
        addChildViewController(HomeViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(DiscoverViewController(), title: "发现", imageName: "tabbar_discover")
        //添加一个空得控制器 占住按钮的位置
         addChildViewController(UIViewController())
        addChildViewController(MessageViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(ProfileViewController(), title: "我", imageName: "tabbar_profile")
        
    }
    
    ///创建一个控制器
    func addChildViewController(vc: UITableViewController, title: String, imageName: String) {
        vc.title = title
        vc.tabBarItem.image = UIImage(named:imageName)
        let nav = UINavigationController(rootViewController: vc)
        addChildViewController(nav)
    }

}
